package cn.xetsoft.supermarket.view.User;

import cn.xetsoft.supermarket.common.DataResponse;
import cn.xetsoft.supermarket.common.SystemData;
import cn.xetsoft.supermarket.dao.impl.UserDaoImpl;
import cn.xetsoft.supermarket.entity.Good;
import cn.xetsoft.supermarket.entity.User;
import cn.xetsoft.supermarket.service.Bean;
import cn.xetsoft.supermarket.service.UserService;
import cn.xetsoft.supermarket.service.impl.UserServiceImpl;
import cn.xetsoft.supermarket.util.GUITools;
import cn.xetsoft.supermarket.util.PropertiesUtil;
import cn.xetsoft.supermarket.util.ViewDataUtil;
import cn.xetsoft.supermarket.view.FuncionFrame;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 管理窗口类
 */
@SuppressWarnings("serial")
public  class UserManagementFrame extends JFrame{
    private UserService userService = Bean.getUserServiceInstance();
    //
    private String jurisdiction;
    //定义界面使用到的组件作为成员变量
    private JScrollPane tablePane = new JScrollPane();//滚动视口
    protected JTable table = new JTable(){
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }; //水果列表

    private JButton addBtn = new JButton("添加用户");//添加按钮
    //修改功能组件
    private JButton updateBtn = new JButton("修改用户");//修改按钮
    //删除功能组件
    private JButton delBtn = new JButton("删除用户");//删除按钮
    //返回功能组件
    private JButton reBtn = new JButton("返回");//删除按钮

    private JLayeredPane layeredPane;
    private ImageIcon image;
    private JPanel jp;
    private JLabel jl;
    //构造方法

    public UserManagementFrame() {
        this.init();// 初始化操作
        this.addComponent();// 添加组件
        this.addListener(this);// 添加监听器
    }
    // 初始化操作
    private void init() {
        this.setTitle("用户管理 - 熵客云超市管理");// 标题
        this.setSize(1286, 642);// 窗体大小与位置
        GUITools.center(this);//设置窗口在屏幕上的位置
        this.setResizable(false);// 窗体大小固定
        LodingUser(this.table);
    }
    // 添加组件
    private void addComponent() {

        layeredPane=new JLayeredPane();
        /**
         * 得到路径区别开发环境和jar包
         */
        String imgFile = "Images/UserManageMnetBgImg.png";
        if (!PropertiesUtil.getProperty("debug.resources.type").equals("jar")){
            imgFile = Class.class.getResource("/").getPath() + imgFile;
        }
        image=new ImageIcon(imgFile);//随便找一张图就可以看到效果。
        //创建背景的那些东西
        jp=new JPanel();
        jp.setBounds(0,-10,image.getIconWidth(),image.getIconHeight());

        jl=new JLabel(image);
//		jl.setBounds(0,0,image.getIconWidth(),image.getIconHeight());
        jp.add(jl);
        //表格
        table.getTableHeader().setReorderingAllowed(false);	//列不能移动
        table.getTableHeader().setResizingAllowed(false); 	//不可拉动表格
//        table.setEnabled(false);							//不可更改数据
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.getTableHeader().setReorderingAllowed(false);
        table.setFillsViewportHeight(true);//确保表永远不会小于视图区
        table.setRowSelectionAllowed(true);//整行选择
//        table.setRowHeight(30);
        tablePane.setBounds(27, 178, 1233, 435);
        tablePane.setViewportView(table);					//视口装入表格
        addBtn.setBounds(43, 120,130, 49);
        updateBtn.setBounds(184, 120,130, 49);
        delBtn.setBounds(322, 120, 130, 49);
        reBtn.setBounds(461, 120, 130, 49);
        //将jp放到最底层。
        layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER);
        //将jb放到高一层的地方
        layeredPane.add(tablePane,JLayeredPane.MODAL_LAYER);
        layeredPane.add(addBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(updateBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(delBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(reBtn,JLayeredPane.MODAL_LAYER);

        this.setLayeredPane(layeredPane);
        this.setSize(image.getIconWidth(),667);
        this.setVisible(true);
        User user = SystemData.getUser();
        System.out.println(user.getRole().getCode());
        jurisdiction = user.getRole().getValue();
    }
    // 添加监听器
    private void addListener(UserManagementFrame userManagementFrame) {
        //添加按钮监听
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //调用添加方法
                new UserAddFrame(userManagementFrame).setVisible(true);
            }
        });
        //修改按钮监听
        updateBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = userManagementFrame.table.getSelectedRow();
                System.out.println("选中的行号" + selectedRow);
                if (selectedRow == -1){
                    System.out.println("未选择");
                    JOptionPane.showMessageDialog(null, "请选择需要修改的用户", "参数问题",JOptionPane.WARNING_MESSAGE);
                }
                Object UserNumber = table.getValueAt(selectedRow, 0);
                /**
                 * 查询id
                 */
                DataResponse<User> userDataResponse = userService.queryById(Integer.valueOf(UserNumber.toString()));
                if (!userDataResponse.isSuccess()){
                    JOptionPane.showMessageDialog(null,userDataResponse.getMsg());
                    return;
                }
                User user = userDataResponse.getData();
                /**
                 * 判断权限
                 */
                if ((jurisdiction.equals("管理员")&&!(user.getRole().getValue().equals("超级管理员")||user.getRole().getValue().equals("管理员"))||jurisdiction.equals("超级管理员"))){
                    new UserModifyFrame(userManagementFrame,user).setVisible(true);
                }else{
                    JOptionPane.showMessageDialog(null,"权限不够");
                }

            }
        });
        //删除按钮监听
        delBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = userManagementFrame.table.getSelectedRow();
                if (selectedRow == -1){
                    System.out.println("未选择");
                    JOptionPane.showMessageDialog(userManagementFrame, "请选择需要删除的用户", "参数问题",JOptionPane.WARNING_MESSAGE);
                }
                Object UserNumber = table.getValueAt(selectedRow, 0);
                /**
                 * 查询优用户
                 */
                DataResponse<User> userDataResponse = userService.queryById(Integer.valueOf(UserNumber.toString()));
                if (!userDataResponse.isSuccess()){ //判断查询的ID是否存在，如果存在才进行赋值
                    JOptionPane.showMessageDialog(null,"获取数据失败！");
                    return;
                }
                User user = userDataResponse.getData(); //获取用户数据
                if ((jurisdiction.equals("管理员")&&!(user.getRole().getValue().equals("超级管理员")||user.getRole().getValue().equals("管理员"))||jurisdiction.equals("超级管理员"))){
                    /**
                     * 删除用户
                     */
                    DataResponse dataResponse = userService.deleteById(Integer.valueOf(UserNumber.toString())); //通过ID删除用户
                    if (dataResponse.isSuccess()){//成功，显示结果数据
                        JOptionPane.showMessageDialog(null,"【成功】:"+dataResponse.getMsg());
                    } else { //失败查看错误信息
                        JOptionPane.showMessageDialog(null,"【失败】:"+dataResponse.getMsg());
                    }
                    LodingUser(userManagementFrame.table);
                }else{
                    JOptionPane.showMessageDialog(null,"权限不够");
                }

            }
        });
        reBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                userManagementFrame.setVisible(false);
            }
        });
    }
    public void LodingUser(JTable table){
        ViewDataUtil viewDataUtil = new ViewDataUtil();
        String[][] tbody = new String[0][];
        DataResponse<List<User>> userDataResponse = userService.queryAll(); //查询所有数据
        if (userDataResponse.isSuccess()){//操作成功
            System.out.println(userDataResponse.getData());
            List<User> UserList = userDataResponse.getData();
            tbody = viewDataUtil.UserlistToArrays(UserList); //将返回对象转换为List方便表格渲染
        } else {
            //不成功打印错误信息
            System.out.println(userDataResponse.getMsg());
        }
        String[] thead = new String[]{"用户编号","用户账户","用户名称","角色","手机号","排班","创建时间","修改时间"};
        TableModel dataModel = new DefaultTableModel(tbody, thead); //表格渲染
        table.setModel(dataModel);
    }

}
